import jobDao from "#/dao/job";
import jobLogDao from "#/dao/job/log";
import type { Task, BaseService } from "#/types";
import {
  getUuid,
  logger,
  getCurrentTime,
  codeSuccess,
  codeFail,
} from "#/utils";
import jobLogService from "./log";
import jobUtil from "./jobUtil";
/**
 * Job实现类
 */
class JobService implements BaseService<Task> {
  async queryList({ page, pageSize, searchContent }) {
    try {
      const r = await jobDao.queryList({ page, pageSize, searchContent });
      const [{ total }] = await jobDao.queryTotal();
      if (r) {
        return codeSuccess({
          items: r,
          total: searchContent ? r.length : total,
        });
      }
      return codeFail("查询失败");
    } catch (error) {
      logger(error);
    }
  }

  async queryAll() {
    try {
      return await jobDao.queryAll();
    } catch (error) {
      logger(error);
    }
  }

  async insert(data: Task) {
    try {
      const created_at = getCurrentTime();
      const updated_at = getCurrentTime();
      const id = getUuid();
      const task = {
        ...data,
        status: 1,
        created_at,
        updated_at,
        id,
      };
      const r = await jobDao.insert(task);
      if (r) {
        jobUtil.create(task, () => {
          const now = new Date();
          logger(`[${now.toLocaleString()}] 🚀 执行任务: ${task.name}`);
          const result = task.push_status
            ? "执行成功,已推送"
            : "执行成功,未推送";
          jobLogService.insert({
            id: getUuid(),
            task_id: task.id,
            task_name: task.name,
            create_time: getCurrentTime(),
            status: 1,
            error_message: "",
            result,
          });
        });
      }
      return codeSuccess(r);
    } catch (error) {
      logger(error);
    }
  }

  async deleteById(id: string) {
    try {
      const r = await jobDao.deleteById(id);
      if (r) {
        return codeSuccess(r);
      }
      return codeFail("删除失败");
    } catch (error) {
      logger(error);
    }
  }

  async update(data: Task) {
    try {
      const r = await jobDao.update({
        ...data,
        updated_at: getCurrentTime(),
      });
      if (r) {
        const [task] = await jobDao.queryById(data.id);
        if (task.status == 1) {
          jobUtil.cancel(data.id);
          jobUtil.restore(data.id);
        }
        return codeSuccess(r);
      }
      return codeFail("更新失败");
    } catch (error) {
      logger(error);
    }
  }
  async updateStatus(data: Task) {
    try {
      const r = await jobDao.updateStatus({
        ...data,
        updated_at: getCurrentTime(),
      });
      if (r) {
        if (data.status == 1) {
          jobUtil.restore(data.id);
        } else {
          jobUtil.cancel(data.id);
        }
        return codeSuccess(r);
      }
      return codeFail("更新失败");
    } catch (error) {
      logger(error);
    }
  }

  async restoreAll(): Promise<void> {
    try {
      return await jobUtil.restoreAll();
    } catch (error) {
      logger(error);
    }
  }

  async queryCount() {
    try {
      const [jobCount] = await jobDao.queryCount();
      const [logCount] = await jobLogDao.queryCount();
      return codeSuccess({ ...jobCount, ...logCount });
    } catch (error) {
      logger(error);
    }
  }
}

export default new JobService();
